<template>
  <div class="app-content flex-column">
    <el-form :model="queryParams" ref="queryRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="用户电话" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="name">
            <el-input v-model="queryParams.name" placeholder="用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="状态">
              <el-option label="待审核" value="1" />
              <el-option label="待启用（通过）" value="2" />
              <el-option label="审核拒绝" value="3" />
              <el-option label="已禁用" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <RichTable class="flex1" ref="richTableRef" height="0" :page="params" :options="options">
      <template #mobile="{ row }">
        <CellPhone :mobile="row.mobile"></CellPhone>
      </template>
      
      <template #status="{ row }">
        <div>
          <!-- 状态(1:待审核,2:有效（通过）,3:审核拒绝,4:已禁用) -->
          <el-tag type="warning" disable-transitions v-if="row.status == 1">待审核</el-tag>
          <el-tag type="success" disable-transitions v-else-if="row.status == 2">有效</el-tag>
          <el-tag type="danger" disable-transitions v-else-if="row.status == 3">审核拒绝</el-tag>
          <el-tag type="info" disable-transitions v-else-if="row.status == 4">已禁用</el-tag>
          <span v-else>--</span>
        </div>
      </template>
    </RichTable>

    <el-drawer :title="`${dialogType=='add'?'新增':'编辑'}电站用户`" v-model="drawerVisible" size="650" append-to-body>
      <el-form label-width="110px" ref="formRef" :model="form" :rules="rules">
        <div class="header">
          <el-icon style="font-size: 20px;color: #8695a1;font-weight: normal;">
            <span class="iconfont icon-jibenxinxi"></span>
          </el-icon>
          <span>电站用户基本信息</span>
        </div>
        <!-- <el-form-item label="bi看板登录名" prop="loginName">
          <el-input placeholder="请输入bi看板登录名" v-model="form.loginName"></el-input>
        </el-form-item> -->
        <el-form-item label="用户名" prop="loginName">
          <el-input placeholder="请输入用户名" v-model="form.loginName"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" prop="mobile">
          <el-input placeholder="请输入用户电话" v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input placeholder="请输入用户名称" v-model="form.name" maxlength="30"></el-input>
        </el-form-item>
        <!-- <el-form-item label="bi看板密码" prop="password">
          <el-input placeholder="请输入" v-model="form.password"></el-input>
        </el-form-item> -->
        <el-form-item label="用户密码" prop="password">
          <el-input placeholder="请输入" v-model="form.password"></el-input>
        </el-form-item>

        <div class="header">
          <div class="header-title">
            <el-icon style="font-size: 20px;color: #8695a1;font-weight: normal;">
              <span class="iconfont icon-shebei1"></span>
            </el-icon>
            <span>关联电站</span>
          </div>
          <div class="header-btn">
            <el-button plain type="primary" size="small" @click="addStation" icon="Plus">新增</el-button>
          </div>
        </div>
        <div class="controller" v-for="(item, index) in form.stationList" :key="'controller' + index">
          <div class="controller-header">
            <div class="controller-header-text">电站{{ index + 1 }}</div>
            <div class="controller-header-close" @click="removeStation(index)">
              <el-icon>
                <Close />
              </el-icon>
            </div>
          </div>
          <div class="controller-conten">
            <el-form-item label="是否管理电站">
              <el-select v-model="item.adminFlag" style="width:100%" placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否查看bi">
              <el-select v-model="item.lookBiFlag" style="width:100%" placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="电站">
              <el-select v-model="item.stationId" style="width:100%" placeholder="请选择" filterable>
                <el-option v-for="(ele, cindex) in userStore.stationList" :key="'powerStationOptions' + cindex"
                  :label="ele.stationName" :value="ele.stationId"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancle">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <el-dialog title="审核电站用户" v-model="dialogVisible" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="formAuditRef" label-width="120px">
        <el-form-item label="用户名">
          <div>{{ form.loginName }}</div>
        </el-form-item>
        <el-form-item label="用户电话">
          <div>{{ form.mobile }}</div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <!-- 状态(1:待审核,2:待启用（通过）,3:审核拒绝,4:运行中 5:关停) -->
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="审核通过" value="2"></el-option>
            <el-option label="审核拒绝" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核说明" prop="auditRemark">
          <el-input v-model="form.auditRemark" placeholder="请输入审核说明" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="handleAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { stationUserApi,stationUserDetailApi,stationUserAuditApi,stationUserChangeStatusApi } from '@/api/station';
import CellPhone from './CellPhone'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
import { ElMessageBox, ElNotification } from "element-plus";
import { Close } from '@element-plus/icons-vue'

// 列表
const richTableRef = ref();
const params = ref({
  page: 1,
  size: 30,
  total:0
})

const options = ref({
  header:false,
  // 表格接口
  tableRequest: {
    url: '/bopeng-cms/station/user/list',
    method: 'get',
    params: {
      stationId:userStore.stationInfo.stationId,
      mobile:'', // 用户电话
      name:'', // 用户名称
      status:'', // 状态
    }
  },
  // 表格操作
  tableEvent: [
    {
      label: "新增",
      title: '新增电站',
      callback: () => {
        form.value.stationList = []
        dialogType.value = 'add'
        drawerVisible.value = true
      }
    }
  ],
  column: [
    { prop: 'loginName', label: '用户名', attrs: { showOverflowTooltip: true } },
    { prop: 'mobile', label: '用户电话', attrs: { width: 160, showOverflowTooltip: true } },
    { prop: 'name', label: '用户名称', attrs: { showOverflowTooltip: true } },
    { prop: 'status', label: '状态', attrs: { width: 100 } },
    { type: 'operation', width:150 },
  ],
  rowEvent: [
    {
      label: "编辑",
      callback: (row) => {
        dialogType.value = 'edit'
        drawerVisible.value = true
        getUserInfo(row.id)
      }
    },
    {
      label: "审核",
      disabled: (row) => {
        return row.status != 1 && row.status != 3
      },
      callback: (row) => {
        dialogVisible.value = true
        getUserInfo(row.id)
      }
    },
    {
      label: "开启",
      disabled: (row) => {
        return row.status != 4 && row.status != 2
      },
      formatter: (row) => {
        if(row.status==4) {
          return '开启'
        }else if(row.status==2) {
          return '关停'
        }
      },
      callback: (row) => {
        ElMessageBox.confirm(`你确定要${row.status==4?'开启':'关停'}【${row.loginName}】？`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          autofocus: false,
          closeOnClickModal: false,
        }).then(async () => {
          // 1:待审核,2:有效（通过）,3:审核拒绝,4:已禁用)
          try {
            let res = await stationUserChangeStatusApi({
              id: row.id,
              status: row.status==4?2:4
            })
            ElNotification({
              title: "成功",
              message: `${row.status==4?'开启':'关停'}成功`,
              type: "success",
            });
            row.status = row.status==4?2:4
          }catch(err) {}
        }).catch(() => {})
      }
    },
  ]
})
const queryParams = toRefs(options.value.tableRequest).params // 保持响应式的解构

/** 搜索按钮操作 */
const handleQuery = () => {
  richTableRef.value.initTable()
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef")
  richTableRef.value.initTable()
}

/** 新增/编辑 */
const drawerVisible = ref(false)
const dialogType = ref('add') // add 新增 edit 编辑
// 当前的表单的实例
const formRef = ref()
const form = ref({
  loginName: '',
  mobile: '',
  name: '',
  password: '',
  stationList: []
})
// 表单校验规则
const rules = reactive({
  loginName: [
    { required: true, message: "用户名不能为空", trigger: ["blur", "change"], },
    {
      pattern: /^[0-9a-zA-Z]{0,16}$/,
      message: "请输入正确的账号格式",
      trigger: ["blur", "change"],
    },
  ],
  mobile: [
    { required: true, message: "用户电话不能为空", trigger: ["blur", "change"], },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的用户电话",
      trigger: ["blur", "change"],
    },
  ],
  name: [
    { required: true, message: "用户名称不能为空", trigger: ["blur", "change"], },
    { max: 30, message: "最长30个字符", trigger: ["blur", "change"], },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: ["blur", "change"], },
    // {
    //   pattern:
    //     /^(?=.*[!"#$%&'()*+,-./\\[\]:;<=>?@^_`{|}~])(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[!"#$%&'()*+,-./\\[\]:;<=>?@^_`{|}~a-zA-Z0-9]{8,20}$/,
    //   message: "请输入8-20位包含大小写字母、数字和特殊符号的密码",
    //   trigger: ["blur", "change"],
    // },
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: ["blur"], },
  ],
  auditRemark: [
    { required: true, message: "审核说明不能为空", trigger: ["blur"], },
  ]
})
//新增 控制器关联
const addStation = () => {
  const temp = {
    adminFlag: "",
    lookBiFlag: "",
    stationId: "",
  }
  form.value.stationList.push(temp)
}
// 删除控制器
const removeStation = index => {
  form.value.stationList.splice(index, 1);
}

//获取用户详情
const getUserInfo = async (id) => {
  try {
    let res = await stationUserDetailApi({id})
    form.value = res.data;
    if(dialogVisible.value) {
      form.value.status = ''
    }
  }catch(err) {}
}

const handleCancle = () => {
  drawerVisible.value = false
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res = await stationUserApi(dialogType.value,form.value)
        ElNotification({
          title: "成功",
          message: `${dialogType.value=='add'?'新增':'编辑'}成功！`,
          type: "success",
        });
        handleCancle()
        handleQuery()
      }catch(err) {}
    }
  })
}

// 审核电站用户
const dialogVisible = ref(false)
const formAuditRef = ref()
const handleAudit = () => {
  formAuditRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res = await stationUserAuditApi(form.value)
        ElNotification({
          title: "成功",
          message: '审核成功！',
          type: "success",
        });
        dialogVisible.value = false
        handleQuery()
      }catch(err) {}
    }
  })
}
</script>

<style lang="scss" scoped>
.app-content {
  height: calc(100vh - 84px);
}

.header {
  color: #253440;
  height: 24px;
  line-height: 24px;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 16px;
  display: flex;
  align-items: center;

  .header-title {
    flex: 1;

    span {
      padding-left: 4px;
    }
  }
}

.controller {
  .controller-header {
    background-color: #F1F5F8FF;
    height: 40px;
    box-sizing: border-box;
    line-height: 20px;
    display: flex;
    padding: 10px 14px;
    margin-bottom: 12px;

    .controller-header-text {
      flex: 1;
      font-size: 14px;
    }

    .controller-header-close {
      cursor: pointer;
      font-size: 12px;
      color: var(--el-color-primary);
    }
  }
}
</style>
